package com.insight.repository;

import com.insight.entity.OperationLog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * OperationLog Repository
 * 操作日志数据访问层
 *
 * @author Insight Team
 */
@Repository
public interface OperationLogRepository extends JpaRepository<OperationLog, Long> {

    /**
     * 按操作类型查询
     */
    Page<OperationLog> findByOperationType(String operationType, Pageable pageable);

    /**
     * 按操作模块查询
     */
    Page<OperationLog> findByOperationModule(String operationModule, Pageable pageable);

    /**
     * 按成功状态查询
     */
    Page<OperationLog> findBySuccess(boolean success, Pageable pageable);

    /**
     * 按时间范围查询
     */
    @Query("SELECT l FROM OperationLog l WHERE l.operationTime BETWEEN :startTime AND :endTime")
    Page<OperationLog> findByTimeRange(
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime,
            Pageable pageable
    );

    /**
     * 按资源查询
     */
    List<OperationLog> findByResourceTypeAndResourceId(String resourceType, Long resourceId);

    /**
     * 统计操作次数
     */
    @Query("SELECT COUNT(l) FROM OperationLog l WHERE l.operationType = :operationType AND l.operationTime >= :since")
    long countByOperationTypeSince(@Param("operationType") String operationType, @Param("since") LocalDateTime since);

    /**
     * 删除过期日志
     */
    void deleteByOperationTimeBefore(LocalDateTime expirationTime);
}
